package com.example.solrdemo.solrtest;

import com.example.solrdemo.entity.Shop;
import com.example.solrdemo.mapper.ShopMapper;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * solr关键字查询测试
 */
@RestController
@RequestMapping("/shop")
public class SolrTest3 {
    public static Logger logger = LoggerFactory.getLogger(SolrTest3.class);
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private SolrClient solrClient;

    //数据库新增数据,并新增索引库
    @RequestMapping("/save")
    public void test1() throws IOException, SolrServerException {
        Shop shop = new Shop();
        shop.setId(UUID.randomUUID().toString().replace("-",""));
        shop.setName("成人水杯");
        shop.setPrice(5.0);
        shop.setTitle("儿童成人都有");
        shop.setDetail("质量好,轻质");
        shop.setAttributes("小型");
        shop.setSpecifications("蓝色,白色");
        shop.setBrand("健力宝");
        shop.setKeySyn("成人");
        shopMapper.save(shop);
        logger.info("数据插入成功");
        solrClient.addBean(shop);
        solrClient.commit();
    }

    /**
     * 关键字查询数据,过滤条件查询数据
     * @param keyWords
     * @param brand
     * @return
     * @throws IOException
     * @throws SolrServerException
     * q:关键字查询 fl:返回字段内容
     * start:0 开始分页 rows:分页
     * wt:指定返回格式 fq:过滤条件
     */
    @RequestMapping(value = "/solr/query",method = RequestMethod.POST)
    public List<Shop> queryBySolr(String keyWords,String brand) throws IOException, SolrServerException {
        List<Shop> list = null;
        if(!StringUtils.isEmpty(keyWords)){
            SolrQuery params = new SolrQuery();
            //根据关键字查询数据
            params.setQuery("key_word:"+keyWords+"OR key_syn:"+keyWords);
            //根据品牌过滤
            if(!"".equals(brand) && brand != null){
                params.set("fq","item_brand:"+brand);
            }
            //设置分页
            params.setStart(0);
            params.setRows(20);
            //排序
            params.setSort("item_name",SolrQuery.ORDER.desc);
            //设置高亮域
            params.setHighlight(true);//开启高亮

            //添加高亮字段
            params.addHighlightField("item_name");
            params.addHighlightField("item_title");
            params.addHighlightField("item_specifications");
            params.addHighlightField("item_brand");
            params.addHighlightField("item_detail");

            params.setHighlightSimplePre("<em style='color:red'>");//设置高亮前缀
            params.setHighlightSimplePost("</em>");//设置高亮后缀

            QueryResponse response = solrClient.query(params);
            SolrDocumentList solrDocument = response.getResults();

            list = new ArrayList<>();

            //将高亮标识加到字段
            Map<String,Map<String,List<String>>> map = response.getHighlighting();

            for(SolrDocument solrDocument1 : solrDocument) {
                Shop shop = new Shop();
                shop.setId(solrDocument1.get("item_id").toString());
                shop.setPrice(Double.parseDouble(solrDocument1.get("item_price").toString()));
                shop.setAttributes(solrDocument1.get("item_attribute").toString());
                shop.setKeySyn(solrDocument1.get("item_syn").toString());
                List<String> nameList= map.get(solrDocument1.get("id")).get("item_name");
                List<String> titleList= map.get(solrDocument1.get("id")).get("item_title");
                List<String> specList = map.get(solrDocument1.get("id")).get("item_specifications");
                List<String> brandList = map.get(solrDocument1.get("id")).get("item_brand");
                List<String> detailList = map.get(solrDocument1.get("id")).get("item_detail");
                String name = "";
                String title = "";
                String spec = "";
                String brand1 = "";
                String detail = "";
                if(nameList != null && nameList.size() > 0){
                    name = nameList.get(0);
                }else {
                    name = solrDocument1.get("item_name").toString();
                }

                if(titleList != null && titleList.size() > 0){
                    title = titleList.get(0);
                }else {
                    title = solrDocument1.get("item_title").toString();
                }

                if(specList != null && specList.size() > 0){
                    spec = specList.get(0);
                }else {
                    spec = solrDocument1.get("item_specifications").toString();
                }

                if(detailList != null && detailList.size() > 0){
                    detail = detailList.get(0);
                }else {
                    detail = solrDocument1.get("item_specifications").toString();
                }

                if(brandList != null && brandList.size() > 0){
                    brand1 = brandList.get(0);
                }else {
                    brand1 = solrDocument1.get("item_brand").toString();
                }
                shop.setDetail(detail);
                shop.setName(name);
                shop.setTitle(title);
                shop.setSpecifications(spec);
                shop.setBrand(brand1);
                list.add(shop);
            }

        }
        return list;
    }

    /**
     * 根据item_id删除索引
     * @param id
     * @return
     * @throws IOException
     * @throws SolrServerException
     */
    @RequestMapping(value = "/solr/delete",method = RequestMethod.POST)
    public String deleteBySolr(String id) throws IOException, SolrServerException {
        //solrClient.deleteById(id);
        solrClient.deleteByQuery("item_id:"+id);
        solrClient.commit();
        return "删除成功";
    }

    @RequestMapping(value = "/saveall",method = RequestMethod.GET)
    public String saveAll() throws IOException, SolrServerException {
        List<Shop> list = shopMapper.query();
        solrClient.addBeans(list);
        solrClient.commit();
        return "索引全部建立成功";
    }


}
